<template>
  <div class="ai-chat-container">
    <h2>AI保险智能对话</h2>
    <div class="ai-chat-history" v-if="chatHistory.length > 0">
      <div v-for="(item, index) in chatHistory" :key="index">
        <div v-if="item.type === 'user'" class="user-message">
          <b>您的提问：</b>
          <div class="message-content">{{ item.message }}</div>
        </div>
        <div v-if="item.type === 'ai'" class="ai-message">
          <b>AI答复：</b>
          <div class="message-content">{{ item.message }}</div>
        </div>
      </div>
    </div>
    <div class="ai-chat-error" v-if="errorMsg">
      {{ errorMsg }}
    </div>
    <div class="ai-chat-form">
      <el-select v-model="aiType" placeholder="请选择保险类型" style="width: 180px;">
        <el-option label="医疗保险" value="医疗保险" />
        <el-option label="事故保险" value="事故保险" />
        <el-option label="财产保险" value="财产保险" />
      </el-select>
      <el-input
        v-model="userInput"
        placeholder="请输入您的保险问题"
        style="width: 300px; margin-left: 10px;"
        @keyup.enter="callAiApi"
      />
      <el-button type="primary" @click="callAiApi" :loading="loading" style="margin-left: 10px;">
        发送
      </el-button>
      <el-button type="danger" @click="clearChatHistory" style="margin-left: 10px;">
        清空对话
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'

const aiType = ref('医疗保险')
const userInput = ref('')
const loading = ref(false)
const errorMsg = ref('')
const chatHistory = ref([])

const callAiApi = async () => {
  if (!userInput.value) {
    errorMsg.value = '请输入您的问题！'
    return
  }
  loading.value = true
  errorMsg.value = ''

  // 添加用户消息到历史记录
  const userMessage = { type: 'user', message: userInput.value }
  chatHistory.value.push(userMessage)

  try {
    const res = await fetch('http://127.0.0.1:8000/ai/session_ai/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: aiType.value,
        user_input: userInput.value,
        history: chatHistory.value
      })
    })
    if (res.ok) {
      const data = await res.json()
      const aiMessage = { type: 'ai', message: data.result || data.answer || JSON.stringify(data) }
      // 添加AI回复到历史记录
      chatHistory.value.push(aiMessage)
    } else {
      const err = await res.json()
      errorMsg.value = err.error || '请求失败'
    }
  } catch (e) {
    errorMsg.value = '网络错误'
  } finally {
    loading.value = false
    userInput.value = ''
  }
}

// const clearChatHistory = async () => {
//   if (chatHistory.value.length === 0) return
//   try {
//     await fetch('http://127.0.0.1:8000/ai/save_history/', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/json'
//       },
//       body: JSON.stringify({
//         user_id: localStorage.getItem('user_id'),
//         type: aiType.value,
//         history: chatHistory.value
//       })
//     })
//   } catch (e) {
//     console.error('保存对话历史记录失败:', e)
//   }
//   chatHistory.value = []
// }

onBeforeUnmount(async () => {
  if (chatHistory.value.length > 0) {
    await clearChatHistory()
  }
})
</script>

<style scoped>
.ai-chat-container {
  max-width: 600px;
  margin: 40px auto;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  padding: 32px 24px 24px 24px;
}
.ai-chat-container h2 {
  text-align: center;
  margin-bottom: 24px;
  color: #409EFF;
}
.ai-chat-form {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
}
.ai-chat-history {
  margin-top: 20px;
}
.user-message,
.ai-message {
  margin-bottom: 16px;
  background: #f5f7fa;
  border-radius: 6px;
  padding: 16px;
  color: #333;
}
.message-content {
  margin-top: 8px;
  font-size: 16px;
  line-height: 1.7;
}
.ai-chat-error {
  margin-top: 20px;
  color: #f56c6c;
  text-align: center;
}
</style>